import { componentMap, asyncRoutes, constantRoutes } from '@/router'
import { getPermission } from '@/api/manage/role'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  directive_permission: [] // 指令权限
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  // 设置指令权限
  SET_DIRECTIVES: (state, directives) => {
    state.directives = directives
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // 从后台请求到的路由
      getPermission().then(response => {
        // 整理后台返回的路由
        let accessedRoutes = response.data.routes.filter(item => {
          return pruningRoutes(item)
        })

        // 拿回后台返回数据后，设置指令权限
        // todo：这里后续还要加整理数据代码，可能后台会返回如下格式 [{"directive":{"name":"sys:role:list","role":["admin","user"]}},{"directive":{"name":"ft:edit_test_case","role":["user"]}}]
        // 最终 directives 保存的是改用户角色下所有的指令权限的字符数组
        const accessedDirectives = response.data.directives
        commit('SET_DIRECTIVES', accessedDirectives)

        accessedRoutes = accessedRoutes.concat(asyncRoutes) // 合并异步路由（例如将404页面合并入可访问路由）
        accessedRoutes = filterAsyncRoutes(accessedRoutes, roles) // 通过递归根据角色过滤异步路由

        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

/**
 * 整理后台返回的路由
 * @param route 路由
 * @returns {{children}|*}
 */
function pruningRoutes(route) {
  // 路由中有 component 属性，将组件字符串转换为组件对象
  if (route.component && typeof route.component === 'string') {
    route.component = componentMap[route.component]
  }

  // 路由中有 props 属性，将 props 字符串转换为 props 对象
  if (route.props && typeof route.props === 'string') {
    route.props = JSON.parse(route.props)
  }

  if (route.children && route.children.length > 0) {
    // 路由中有 children，循环递归处理 children
    for (let i = 0; i < route.children.length; i++) {
      pruningRoutes(route.children[i])
    }
  } else {
    // 删除空 children。不删 alwaysShow 设置参数会失效
    delete route.children
  }

  return route
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
